package com.example.campsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.campsystem.config.WechatConfig;
import com.example.campsystem.entity.User;
import com.example.campsystem.mapper.UserMapper;
import com.example.campsystem.service.WechatService;
import com.example.campsystem.tool.OSSFileUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class WechatServiceImpl extends ServiceImpl<UserMapper,User> implements WechatService {
    private final WechatConfig wechatConfig;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    @Override
    public User loginWithWechat(String code, User userInfo) {
        try {
            // 1. 通过code获取openid和session_key
            String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    wechatConfig.getAppId(), wechatConfig.getAppSecret(), code);

            String result = restTemplate.getForObject(url, String.class);
            JsonNode node = objectMapper.readTree(result);
            String openId = node.get("openid").asText();
            // String sessionKey = node.get("session_key").asText();
            System.out.println(openId);

            // 3. 查询用户是否存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("openId", openId);  // 修改这里，使用正确的列名
            User existUser = this.baseMapper.selectOne(queryWrapper);
            
            if (existUser == null) {
                // 3. 新用户，保存到数据库
                User newUser = new User();
                newUser.setOpenid(openId);
                newUser.setNickname(userInfo.getNickname());
                newUser.setAvatarurl(userInfo.getAvatarurl());
                newUser.setStatus(1);
                newUser.setCreatedat(new Date());
                newUser.setUpdatedat(new Date());
                this.baseMapper.insert(newUser);
                return newUser;
            } else {
                return existUser;
            }
        } catch (Exception e) {
            throw new RuntimeException("微信登录失败: " + e.getMessage());
        }
    }
}